import 'dart:math';
import 'package:flutter/material.dart';

import 'package:flutter_example/request/http_client.dart';
import './quiz.dart';

class QuizPage extends StatelessWidget {
  const QuizPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Quiz"),
        elevation: 0.0,
      ),
      body: Home(),
    );
  }
}

class Home extends StatefulWidget {
  Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  late Quiz quiz;
  late List<Results> results;
  late Color c;
  Random random = Random();

  Future<void> fetchQuestions() async {
    var res = await HttpClient().get("https://opentdb.com/api.php?amount=20");
    quiz = Quiz.fromJson(res.data);
    results = quiz.results!;
  }
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: fetchQuestions,
      child: FutureBuilder(
        future: fetchQuestions(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          switch(snapshot.connectionState) {
            case ConnectionState.none:
              return Text('Press button to start');
            case ConnectionState.active:
            case ConnectionState.waiting:
              return Center(child: CircularProgressIndicator());
            case ConnectionState.done:
              if (snapshot.hasError) return errorData(snapshot);
              return questionList();
          }
        }
      ), 
    );
  }

  Padding errorData(AsyncSnapshot snapshot) {
    return Padding(
      padding: const EdgeInsets.all(12),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('Error: ${snapshot.error}'),
          const SizedBox(height: 20.0),
          ElevatedButton(
            onPressed: () {
              fetchQuestions();
              setState(() {});
            }, 
            child: const Text("Try Again"),
          ),
        ],
      ),
    );
  }

  ListView questionList() {
    return ListView.builder(
      itemCount: results.length,
      itemBuilder: (context, index) => Card(
        color: Colors.white,
        elevation: 0.0,
        child: ExpansionTile(
          title: Padding(
            padding: const EdgeInsets.all(18.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                Text(
                  results[index].question!,
                  style: const TextStyle(
                    fontSize: 18.0,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                FittedBox(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      FilterChip(
                        backgroundColor: Colors.grey,
                        label: Text(results[index].category!), 
                        onSelected: (b) {},
                      ),
                      const SizedBox(width: 10.0),
                      FilterChip(
                        backgroundColor: Colors.grey[100],
                        label: Text(results[index].difficulty!),
                        onSelected: (b) {},
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          leading: CircleAvatar(
            backgroundColor: Colors.grey[100],
            child: Text(results[index].type!.startsWith("m") ? "M" : "B"),
          ),
          children: results[index].allAnswers!.map((e) {
            return AnswerWidget(results, index, e);
          }).toList(),
        )
      )
    );
  }
}

class AnswerWidget extends StatefulWidget {
  final List<Results> results;
  final int index;
  final String m;
  AnswerWidget(this.results, this.index, this.m);
  @override
  _AnswerWidgetState createState() => _AnswerWidgetState();
}

class _AnswerWidgetState extends State<AnswerWidget> {
  Color c = Colors.black;
  @override
  Widget build(BuildContext context) {
    return ListTile(
      onTap: () {
        setState(() {
          if (widget.m == widget.results[widget.index].correctAnswer) {
            c = Colors.green;
          } else {
            c = Colors.red;
          }
        });
      },
      title: Text(
        widget.m,
        textAlign: TextAlign.center,
        style: TextStyle(
          color: c,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }
}